package com.song.proxy;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description: JDKProxyUtil：类描述
 * @author: songzhangyong
 * @Date: 2019/11/1 17:22
 */
public class JDKProxyUtil {

	public static void main(String[] args) {
		IUserService ss = (IUserService) Proxy.newProxyInstance(
				IUserService.class.getClassLoader(), new Class[]{IUserService.class},
				new MyInvocationHandler(new UserServiceImpl()) );
//		ss.query("fdfdfd");
		ss.save("fdfdfd"  , 1);
		System.out.println();

	}

	static class MyInvocationHandler implements InvocationHandler{

		private final IUserService user;

		public MyInvocationHandler(IUserService user){
			this.user = user;
		}

		/**
		 *
		 * @param proxy		就是代理对象，newProxyInstance方法的返回对象
		 * @param method	调用的方法
		 * @param args		方法中的参数
		 * @return
		 * @throws Throwable
		 */
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			System.out.println("---------before-------"+method.getName());
			method.invoke(user, args);
			System.out.println("---------after-------");
			if ("method".equals(method.getName())) {
				return method.invoke(user, null);
			}
			return null;
		}
	}

	static class MyInvocationHandler2 implements InvocationHandler{

		Object tareg;

		public MyInvocationHandler2(Object user){
			this.tareg = tareg;
		}

		/**
		 *
		 * @param proxy		就是代理对象，newProxyInstance方法的返回对象
		 * @param method	调用的方法
		 * @param args		方法中的参数
		 * @return
		 * @throws Throwable
		 */
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			System.out.println("---------before-------"+method.getName());
			method.invoke(tareg, args);
			System.out.println("---------after-------");
			if ("method".equals(method.getName())) {
				return method.invoke(tareg, null);
			}
			return null;
		}
	}

}
